<template>
  <div class="edit">
    <el-dialog :title="prop.title" :visible.sync="prop.open" width="680px" :close-on-click-modal="false" :show-close="false" destroy-on-close append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="员工工号" prop="employeeCode">
              <el-select
                style="width: 100%;"
                v-model="form.employeeCode"
                filterable
                remote
                reserve-keyword
                placeholder="请输入员工工号"
                :remote-method="getEmployeeCodeSelectItems"
                :loading="employeeCodeLoading">
                <el-option
                  v-for="item in employeeCodeData"
                  :key="item.employeeCode"
                  :label="item.employeeName"
                  :value="item.employeeCode">
                  {{item.employeeName+'-'+item.employeeTel+'-'+item.employeeCode}}
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="合同标题" prop="employeeContractName">
              <el-input v-model="form.employeeContractName" placeholder="长度1-30字符"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="合同类型" prop="employeeContractType">
              <el-select v-model="form.employeeContractType" placeholder="请选择类型" >
                <el-option
                  v-for="item in dict.type.contract_type"
                  :key="item.raw.dictCode"
                  :label="item.raw.dictLabel"
                  :value="item.raw.dictCode">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同期限" prop="employeeContractTerm">
              <el-input placeholder="合同期限" v-model.number="form.employeeContractTerm">
                <el-form-item prop="employeeContractTermUnit" slot="append">
                  <el-select v-model="form.employeeContractTermUnit"  placeholder="单位" size="mini" style="width: 65px;">
                    <el-option label="年" value="0"></el-option>
                    <el-option label="月" value="1"></el-option>
                    <el-option label="周" value="2"></el-option>
                    <el-option label="日" value="3"></el-option>
                  </el-select>
                </el-form-item>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="合同有效期" prop="range">
              <el-date-picker
                  v-model="form.range"
                  type="daterange"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  style="width: 100%;">
                </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="签订日期" prop="employeeContractSignTime">
              <el-date-picker
                  v-model="form.employeeContractSignTime"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  type="date"
                  placeholder="请选择签订日期">
                </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="存放地点" prop="employeeStorageLocation">
              <el-input v-model="form.employeeStorageLocation" type="textarea" placeholder="1-300字符"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="合同说明" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="1-300字符"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="盖章状态" prop="employeeContractStamp">
              <el-switch
                @change="changeStatus"
                v-model="form.employeeContractStamp"
                active-value="1"
                inactive-value="0"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="是"
                inactive-text="否">
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="领取状态" prop="employeeContractReceive">
              <el-switch
                @change="changeStatus"
                v-model="form.employeeContractReceive"
                active-value="1"
                inactive-value="0"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="是"
                inactive-text="否">
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="附件" prop="fileIds">
              <el-upload
                :action="action"
                :on-remove="delFile"
                :headers="headers"
                :before-upload="handleBeforeUpload"
                :on-success="handleUploadSuccess"
                :file-list="fileList">
                <el-button size="small" type="primary">点击上传</el-button>
                <span slot="tip" style="color:red;margin-left: 5px;">单个文件不超过200m</span>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :loading="saveLoading">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {add,edit,getDetail,checkEmployeeCodeisExist,getEmployeeCodeSelectItems} from '@/api/employee/employeeContract/employeeContract.js'
import {uploadUrl,uploadHeaders,deleteFile } from '@/api/file/file.js'
import {commonFileType} from '@/utils/constants/common/constants.js'
export default {
  name: "ContractEdit",
  components:{},
  dicts:['contract_type'],
  props:{
    prop:{
      type:Object,
      default:function(){
        return {
          title:'新增合同/协议',
          id:null,
          open:false,
        }
      }
    }
  },
  data(){
    var employeeCodeValidator = (rule, value, callback) => {
      if(value!==null&&value.trim()!==""){
        checkEmployeeCodeisExist({employeeCode:value}).then(res =>{
          let isExist = res.data
          if (isExist) {
            return callback()
          }else{
            return callback(new Error('员工工号不存在'));
          }
        })
      }else{
         return callback(new Error('请输入员工工号'));
      }
    };
    return{
      saveLoading:false,
      open:this.prop.open,
      isEdit:false,
      typeData:[
        {value:'0',label:'试用期劳动合同'},
        {value:'1',label:'正式劳动合同'},
        {value:'2',label:'协议'},
        {value:'3',label:'劳务派遣合同'},
      ],
      employeeCodeData:[],
      employeeCodeLoading:false,
      form: {
        employeeId:null,
        employeeCode:null,
        employeeContractId:null,
        employeeContractCode:null,
        employeeContractName: null,
        employeeContractType:null,
        employeeContractTerm: null,
        employeeContractTermUnit:'0',
        employeeContractSignTime:null,
        employeeContractStartTime:null,
        employeeContractEndTime:null,
        employeeContractStamp:'0',
        employeeContractStampTime:null,
        employeeContractReceive:'0',
        employeeContractReveiveTime:null,
        employeeStorageLocation:null,
        remark:null,
        fileIds:[],
        range:[],
        isEnable:'0'
      },
      action:uploadUrl,
      fileType:commonFileType,
      fileSize:200,
      oldFileList:[],
      fileList:[],
      headers:uploadHeaders,
      rules: {
        employeeCode: [
          { required: true, validator:employeeCodeValidator, trigger: 'blur' },
        ],
        employeeContractName: [
          { required: true, message: '请输入合同标题', trigger: 'blur' },
          { min: 1, max: 30, message: '长度在1-30个字符', trigger: 'blur' }
        ],
        employeeContractType: [
          { required: true, message: '请选择合同类型', trigger: 'change' },
        ],
        employeeContractTerm: [
          { required: true, message: '请选择合同年限', trigger: 'change' },
        ],
        employeeContractTermUnit: [
          { required: true, message: '请选择期限单位', trigger: 'change' },
        ],
        employeeContractSignTime: [
          { required: true, message: '请选择签订时间', trigger: 'change' },
        ],
        range: [
          { required: true, message: '请选择合同时间段', trigger: 'blur' },
        ],
        employeeContractStamp: [
          { required: true, message: '请选择盖章状态', trigger: 'blur' },
        ],
        employeeContractReceive: [
          { required: true, message: '请选择领取状态', trigger: 'blur' },
        ],
        employeeStorageLocation: [
          { required: false, message: '请输入存放地点', trigger: 'blur' },
        ],
        fileIds: [
          { required: true, message: '请上传附件', trigger: 'blur' },
        ],
      }
    }
  },
  methods:{
    getDetail(){
      getDetail({employeeContractId:this.prop.id}).then(res =>{
        let data = res.data
        data.contract.range = [data.contract.employeeContractStartTime,data.contract.employeeContractEndTime]
        if(data.files!==null){
          this.fileList = data.files.map(item =>{
            return {fileId:item.fileId,name:item.fileOriginalName}
          })
          data.contract.fileIds = data.files.map(item=>item.fileId)
        }else{
          data.contract.fileIds = []
          console.log('合同详情中附件信息不存在')
        }
        this.form = data.contract
        //合同类型需要数字类型，单独处理
        this.form.employeeContractType = Number.parseInt(this.form.employeeContractType)
      }).catch(err =>{
        console.log('查询合同详情失败，原因：',err)
      })
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      if (this.fileType) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        const isTypeOk = this.fileType.some((type) => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
        if (!isTypeOk) {
          this.$message.error(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
          return false;
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      return true;
    },
    // 上传成功回调
    handleUploadSuccess(res, file,fileList) {
      if(res.code === 200){
        this.form.fileIds.push(res.data)
      }else{
        this.$message.error('上传文件失败，请稍后再试')
      }
    },
    // 上传失败
    handleUploadError(err, file, fileList) {
      this.$message.error("上传附件失败, 请重试");
    },
    delFile(file,fileList){
      if(file.fileId || file.response){
        let fileId = null
        if(file.fileId){
          fileId = file.fileId
        }else{
          fileId = file.response.data
        }
        //删除已提交文件
        if(fileId!==null){
          deleteFile({fileId:fileId}).then(res =>{
            let delIndex = this.form.fileIds.findIndex(item =>item === fileId)
            if(delIndex>-1){
              this.form.fileIds.splice(delIndex,1)
            }
            let fileDelIndex = this.fileList.findIndex(item =>item.fileId === fileId)
            if(fileDelIndex>-1){
              this.fileList.splice(fileDelIndex,1)
            }
          }).catch(err =>{
            console.log('删除文件失败，原因：',err)
            this.fileList = this.oldFileList
          })
        }
      }
    },
    getEmployeeCodeSelectItems(val){
      if(val!==''){
        getEmployeeCodeSelectItems({employeeCode:val}).then(res =>{
          this.employeeCodeData = res.data
        }).catch(err =>{
          console.log('查询员工工号下拉数据失败，原因：',err)
        })
      }else{
        this.employeeCodeData = []
      }
    },
    changeStatus(status){
      this.$confirm('是否修改？','确认信息',{
        distinguishCancelAndClose: true,
        confirmButtonText: '确认',
        cancelButtonText: '取消'
      }).then(()=>{
        this.form.employeeContractStamp = status
      }).catch(action => {
        this.form.employeeContractStamp = status === '1'?'0':'1'
      });
    },
    setFormData(){
      this.form.employeeContractStartTime = this.form.range[0]
      this.form.employeeContractEndTime = this.form.range[1]
      let {fileIds,...contract} = this.form
      let files  = []
      if(fileIds){
        files = fileIds.map(item =>{
          return {fileId:item}
        })
      }
      return {files:files,contract:contract}
    },
    /** 提交按钮 */
    submitForm: function() {
      this.saveLoading = true
      this.$refs["form"].validate(valid => {
        if (valid) {
          //对表单数据进行处理
          let formData = this.setFormData()
          if (this.isEdit) {
            edit(formData).then(response => {
              this.saveLoading = false
              this.$modal.msgSuccess("修改成功");
              this.cancel()
            }).catch(err =>{
              console.log('保存失败，原因：',err)
              this.saveLoading = false
            });
          } else {
            add(formData).then(response => {
              this.saveLoading = false
              this.$modal.msgSuccess("新增成功");
              this.cancel()
            }).catch(err =>{
              console.log('保存失败，原因：',err)
              this.saveLoading = false
            });
          }
        }else{
          this.saveLoading = false
        }
      });
    },
    // 表单重置
    reset() {
      this.form = {
        employeeId:null,
        employeeCode:null,
        employeeContractId:null,
        employeeContractCode:null,
        employeeContractName: null,
        employeeContractType:null,
        employeeContractTerm: null,
        employeeContractTermUnit:'0',
        employeeContractSignTime:null,
        employeeContractStartTime:null,
        employeeContractEndTime:null,
        employeeContractStamp:'0',
        employeeContractStampTime:null,
        employeeContractReceive:'0',
        employeeContractReveiveTime:null,
        fileIds:[],
        range:[],
        isEnable:'1'
      };
      this.isEdit = false
    },
    cancel(){
      this.$emit('close')
    }
  },
  mounted() {
    if(this.prop.id!=null){
      this.isEdit = true
      this.getDetail()
      console.log(this.isEdit)
    }
  },
  updated() {

  },
}
</script>

<style lang="less" scoped>

</style>
